package com.yuanzheng.test.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 */
@Component
public class JedisManagerUtil {

    @Autowired
    private JedisConfig jedisConfig;
    /**
     * 统一管理Jedis对象
     */
    private Map<Integer, Jedis> jedisMap = new HashMap<>(16);

    /**
     * 写入数据
     *
     * @param key      redis的key
     * @param value    redis的value
     * @param database 写入的库index
     * @return 写入结果
     */
    public synchronized String setCache(String key, String value, int database) {
        if (!jedisMap.containsKey(database)) {
            String host = jedisConfig.getHost();
            int port = jedisConfig.getPort();
            Jedis jedis = new Jedis(host, port);
            jedis.select(database);
            jedisMap.put(database, jedis);
            return jedis.set(key, value);
        } else {
            Jedis jedis = jedisMap.get(database);
            return jedis.set(key, value);
        }
    }
}
